<!-- src/views/admin/PermissionsList.vue -->
<template>
  <div class="perms-page">
    <el-card class="perms-card" :body-style="{ padding: '20px' }">
      <div class="toolbar">
        <el-input
          v-model="filters.name"
          placeholder="权限名称"
          clearable
          @clear="fetchList"
          @keyup.enter="fetchList"
          size="small"
          class="toolbar-item"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="small" class="toolbar-btn" @click="openDialog()">
          新增权限
        </el-button>
        <el-button
          type="danger"
          size="small"
          class="toolbar-btn"
          :disabled="!multiple.length"
          @click="onBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="list"
        stripe
        highlight-current-row
        @selection-change="multiple = $event"
        class="perms-table"
      >
        <el-table-column align="center" type="selection" width="50" />
        <el-table-column align="center" prop="id" label="ID" width="80" />
        <el-table-column align="center" prop="name" label="权限名称" />
        <el-table-column align="center" prop="description" label="权限描述" />
        <el-table-column align="center" label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" class="action-btn" @click="openDialog(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" class="action-btn danger" @click="onDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper, sizes, total"
          :current-page="pageNum"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          :total="total"
          @current-change="onPageChange"
          @size-change="onSizeChange"
        />
      </div>
    </el-card>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" class="perms-dialog">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="perms-form">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="如 user:create" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入权限描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="onSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  pagePermissions,
  createPermission,
  updatePermission,
  deletePermissions,
} from "@/api/rolePermissions";

const filters = reactive({ name: "" });
const loading = ref(false);
const list = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const multiple = ref([]);

const dialogVisible = ref(false);
const isCreate = ref(true);
const dialogTitle = ref("新增权限");
const form = reactive({ id: null, name: "", description: "" });
const formRef = ref(null);
const saving = ref(false);

const rules = {
  name: [
    { required: true, message: "请输入权限名称", trigger: "blur" },
    {
      pattern: /^[a-z]+:[a-z]+$/,
      message: "格式应为 resource:action，例如 user:create",
      trigger: "blur",
    },
  ],
};

async function fetchList() {
  loading.value = true;
  const res = await pagePermissions({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    name: filters.name,
  });
  list.value = res.data.items;
  total.value = res.data.total;
  loading.value = false;
}

function onPageChange(p) {
  pageNum.value = p;
  fetchList();
}
function onSizeChange(s) {
  pageSize.value = s;
  pageNum.value = 1;
  fetchList();
}

function openDialog(row) {
  if (row) {
    isCreate.value = false;
    dialogTitle.value = "编辑权限";
    Object.assign(form, row);
  } else {
    isCreate.value = true;
    dialogTitle.value = "新增权限";
    form.id = null;
    form.name = "";
    form.description = "";
  }
  dialogVisible.value = true;
}

function onSubmit() {
  // 先校验表单
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    saving.value = true;
    try {
      if (isCreate.value) {
        await createPermission({
          name: form.name,
          description: form.description,
        });
        ElMessage.success("新增成功");
      } else {
        await updatePermission({
          id: form.id,
          name: form.name,
          description: form.description,
        });
        ElMessage.success("更新成功");
      }
      dialogVisible.value = false;
      fetchList();
    } finally {
      // 无论成功还是失败，都要重置 saving
      saving.value = false;
    }
  });
}

function onDelete(row) {
  ElMessageBox.confirm("确认删除？", "提示", { type: "warning" }).then(
    async () => {
      await deletePermissions([row.id].join(","));
      ElMessage.success("删除成功");
      fetchList();
    }
  );
}
function onBatchDelete() {
  ElMessageBox.confirm("确认删除选中？", "提示", { type: "warning" }).then(
    async () => {
      await deletePermissions(multiple.value.map((i) => i.id).join(","));
      ElMessage.success("批量删除成功");
      multiple.value = [];
      fetchList();
    }
  );
}

onMounted(fetchList);
</script>
  
<style scoped>
.perms-page {
  background: #f6f8fa;
  min-height: 100vh;
  padding: 24px;
}

.perms-card {
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.08);
  background: #fff;
  transition: box-shadow 0.3s;
}
.perms-card:hover {
  box-shadow: 0 4px 12px rgba(99,102,241,0.08);
}

.toolbar {
  margin-bottom: 18px;
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}
.toolbar-item {
  width: 220px;
}
.toolbar-btn {
  border-radius: 8px;
  transition: all 0.2s;
}
.toolbar-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(99,102,241,0.08);
}

.perms-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 18px;
}
.perms-table :deep(.el-table__row) {
  transition: background 0.2s, box-shadow 0.2s;
}
.perms-table :deep(.el-table__row:hover) {
  background: #f5f7fa !important;
  box-shadow: 0 2px 8px rgba(99,102,241,0.04);
}
.action-btn {
  color: #6366f1;
  font-weight: 500;
  margin-right: 8px;
  transition: color 0.2s, transform 0.2s;
}
.action-btn:last-child {
  margin-right: 0;
}
.action-btn:hover {
  color: #3b82f6;
  transform: translateY(-1px);
}
.action-btn.danger {
  color: #ef4444;
}
.action-btn.danger:hover {
  color: #b91c1c;
}

.pagination {
  text-align: right;
  margin-top: 12px;
}

.perms-dialog :deep(.el-dialog__header) {
  padding: 20px 24px 10px 24px;
  border-bottom: 1px solid #f0f0f0;
}
.perms-dialog :deep(.el-dialog__body) {
  padding: 24px 24px 0 24px;
}
.perms-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}
.perms-form {
  margin-top: 12px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 900px) {
  .perms-page {
    padding: 12px;
  }
  .toolbar-item {
    width: 100%;
  }
  .perms-card {
    padding: 0;
  }
}
@media (max-width: 600px) {
  .toolbar {
    flex-direction: column;
    gap: 8px;
  }
  .perms-table {
    font-size: 13px;
  }
  .perms-dialog :deep(.el-dialog__body) {
    padding: 12px 8px 0 8px;
  }
}
</style>
  